<template>
    <massif-layout leftWidth="300px" leftHeight="calc(100vh - 140px)" :showBack="false" @back="goBack">
        <template v-slot:left>
            <div class="receive-land-left-view">
                <landTotal :farmcount="farmcount" />
                <LandList :tableData="tableData" 
                :pageInfo="searchInfo" 
                @onClick="setMapData"
                showDelete
                @onDelete="btnDel" @page-change="toPage"  />
            </div>
        </template>
        <mapContainer domId="receive-dom" @init="initMap" @zoom="zoomMap" searchLeft="330px" searchTop="20px" @click="clickMap"  @pointerMove="pointerMove" />
        
        <div class="bottom-view-tips">
            <div style="background-color: rgb(43, 129, 212, 1);border:1px solid rgb(43, 129, 212, 1);">待认领</div>
            <div style="background-color: #25c289;border:1px solid #25c289;">已认领</div>
            <div>被认领</div>
        </div>
        <PoiPopup v-if="showPop &&currentZoom>12" :popOption="popObjct"  @click="clickLand" @onClose="(type)=>{showPop=type}" />

        <div class="land-detail" v-if="showDetail">
            <land-detail :farmLandId="dropFarmLandId" 
            @clickDel="btnDel" 
            @eidt="eidtClick"             
            :farmLandNo="dropFarmLandNo"
            :farmLandPic="dropFarmLandPic" @close="showDetail=false"/>
        </div>

    </massif-layout>
</template>
  
  <script setup>
  // 这里的name是为了做页面缓存，其值要跟路由里面的name值一样
  
  import { nextTick, ref, watch, onActivated,reactive,onMounted} from 'vue'
  import{useRouter,useRoute} from "vue-router"
  import {getFarmCount,releaseFarmland,getCompositeFarmland,claimLand,uploadFile,tancLand} from '@/api/gis'
  import {getLandList,getLandGroupList} from '@/api/plant'
  import {message} from '@/utils/element'
  import myPagination from '@/components/custom/myPagination.vue'
  import massifLayout from '../components/layout.vue'
  import groupSelect from '@/components/custom/groupSelect.vue'
  import landSelect from '@/components/custom/landSelect.vue'
  import cDialog from '@/components/custom/cDialog.vue'
  import { useUserStore } from '@/pinia/modules/user'
  import cropSelect from '@/components/custom/cropSelect.vue'
  import Image from '@/components/custom/image.vue'
  import CountUp from 'vue-countup-v3'
  import landDetail from './landDetail.vue'
  import  mapContainer from '@/components/Map/index.vue'
  import {WktToPolygon } from '@/components/Map/utils/geoToWkt';
  import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer"
  import Graphic from "@arcgis/core/Graphic"
  import * as webMercatorUtils from "@arcgis/core/geometry/support/webMercatorUtils.js";
  import PoiPopup from '@/components/Map/components/PoiPopup.vue';
  import Point from '@arcgis/core/geometry/Point.js';
  import {VXETable} from 'vxe-table'
  import landTotal from './components/landTotal.vue'
  import LandList from './components/landList.vue'

  const emit = defineEmits(['close','eidt'])

  const router = useRouter()
  const userStore = useUserStore()
  const page = ref(1)
  const limit = ref(10)
  const total = ref(0)
  const dropFarmLandId = ref('') // 下拉选择地块id
  const dropFarmLandNo = ref('') // 下拉选择地块id
  const dropFarmLandPic = ref('') 
  const tableData = ref([])
  const mapList = ref([])
  const farmcount = ref({farmLandTotal:0,farmLandCount:0})
  const showDetail = ref(false)
  const currentZoom= ref(5)
 const clickRow = ref(null)
 const showPop = ref(false)
 const urlImage = ref(import.meta.env.VITE_BASE_PATH)
 const popObjct = ref({})
 const dragMapList = ref([])
 const searchInfo = ref({page: 1, limit: 10,total: 0})

  let mapView =null
  let graphicsLayer = null
  let extentTimer=null
    onMounted(()=>{
        VXETable.modal.message({ content: '点击地块认领', status: 'warning',duration:5000})
        VXETable.modal.message({ content: '如自己地块被其他农场认领可申述', status: 'warning',duration:10000})
    })
    const getMapDataLand =()=>{
        if(extentTimer) {
                clearTimeout(extentTimer)
            }
            extentTimer = setTimeout(() => {
                getMapList({
                    locationLongitude:mapView.extent.center.longitude,
                    locationLatitude:mapView.extent.center.latitude
                },2)
            }, 1000)
    }
  const initMap = (map)=>{
    mapView = map
    get_land_list() 
    get_farm_count()
    if(!userStore.userInfo.farmList.length){ return }
    let info = userStore.userInfo.farmList.find((item)=>item.farmId==userStore.userInfo.farmId)
    getMapList(info,1)
        mapView.on('drag', (e) => {
            getMapDataLand()
        })
        mapView.on('mouse-wheel', (e) => {
            getMapDataLand()
        })
  }

  //地块统计
  const get_farm_count = ()=>{
    getFarmCount({
        landSource:2,
        farmId:userStore.userInfo.farmId
    }).then(res =>{
        if(res.success){
            farmcount.value = res.data
        }
    })
  }

  //已认领列表
  const get_land_list = async ()=>{
    const res = await getLandList({
        page:searchInfo.value.page,
        limit:searchInfo.value.limit,
        landSource:2,
        farmId:userStore.userInfo.farmId
    })
    if(res.success){
        tableData.value = res.data
        searchInfo.value.total = res.total || 0

    }
  }


  
  //地图地理gis绘制信息数据
  const getMapList=async(row,type)=>{
    if(dragMapList.value.includes(row.locationLongitude) || (currentZoom.value<12 && type !=1)){
        return
    }
    dragMapList.value.push(row.locationLongitude)
    const res = await getCompositeFarmland({
        bufferRange:(6000/currentZoom.value)>500?500:(5000/currentZoom.value),
        landSource:2,
        point:`point(${row.locationLongitude} ${row.locationLatitude})`,
    }) 
    if(res.success){
        mapList.value = res.data ||[]
        drawLandList(mapList.value,{locationLongitude:row.locationLongitude,locationLatitude:row.locationLatitude},type)
    }
  } 

const zoomMap=(val)=>{
  currentZoom.value = val
  if(graphicsLayer){
        const graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type == 'text')
        graphics.forEach(item => {item.visible = val > 17 ? true : false})
   }
   getClickData()
}

const pointerMove=(val)=>{
   getClickData()
}

const eidtClick=(data)=>{
    emit('eidt',data)
}

const clickMap =(e,e2)=>{
     if(e2.results.length>0){
          e2.results.forEach(e3 => {
          let attrs = e3.graphic.attributes
         if(attrs?.class == "click-landMark") { 
           clickRow.value = mapList.value.find((item)=>item.farmLandId==attrs.farmLandId)
           getClickData()
           showPop.value=true
         }
        })
      }
 }

//地块绘制到地图
const drawLandList = (dataList,center,onType)=>{
  if(!graphicsLayer){
    graphicsLayer = new GraphicsLayer({ id:'receive-land-plot'});
  }else{
    //graphicsLayer.removeAll()
  }
  dataList.forEach((item,index)=>{
    if(item.geom){
        const geo = WktToPolygon(item.geom, { wkid: 4326 });
        const newGeo = webMercatorUtils.geographicToWebMercator(geo)
        const polygon = new Graphic({
          geometry: newGeo,
          symbol: {
            type: 'simple-fill',
            color:(item.farmId !=0&& userStore.userInfo.farmId!=item.farmId)?'#f5ce0d00':(userStore.userInfo.farmId==item.farmId?[43, 129, 212, 0]:[43, 129, 212, 0]),
            outline: {
                color: (item.farmId !=0&& userStore.userInfo.farmId!=item.farmId)?'#f5ce0d':(userStore.userInfo.farmId==item.farmId?'#25c289':[43, 129, 212, 1]),
                width: 1
            }
          },
          attributes: {
            class: 'click-landMark',
            farmLandId:item.farmLandId,
            ...item
          }
          })
          const textAreaStyle = {
              type: "text", 
              color: [255, 255, 255],
              haloColor: [0, 0, 0],
              haloSize: "1px",
              text: "",
              xoffset: 0,
              yoffset: 0,
              cursor: 'pointer',
              font: {
                size: 10,
                family: "PingFangSC",
                weight: "bold"
              }
          }
          const AreaGeometry = polygon.geometry.extent.center
          const areaValue = Number(item.mapAreaSize.toFixed(1))
          let result = "";
          for (let i = 0, len = item.farmLandName.length; i < len; i++) {
            if (i % 8 === 0 && i != 0) result += '\n';
            result += item.farmLandName[i];
            }
          textAreaStyle.text = `${result}\n${areaValue}亩`
          const textAttr = { ...item, type: 'text' }
          const textAreaGraphic = new Graphic({
              geometry: AreaGeometry,
              symbol: textAreaStyle,
              attributes: textAttr,
              visible: currentZoom.value>14?true:false
            })
            const graphics = graphicsLayer.graphics.items.find((m) => m.attributes.farmLandId == item.farmLandId)
            if(!graphics){
                graphicsLayer.add(polygon);
                graphicsLayer.add(textAreaGraphic)
            }
     }
  })
    //画边形
    mapView.map.add(graphicsLayer)
    //定位
    setTimeout(() => {
        if(onType==1){
            // mapView.goTo(graphicsLayer.graphics.items);
            mapView.set({zoom:18,center: [center.locationLongitude, center.locationLatitude]})
        }else{
            mapView.set({center: [center.locationLongitude, center.locationLatitude]})
        }
    }, 500);
}

  // 设置选中高亮
const setSelectLine = ({ row, rowIndex }) =>{
    if(row.farmLandId == dropFarmLandId.value){
        return "selectedStyle"
    }else{
        return ''
    }
  }

  
//点击坐标点的弹出框数据
const getClickData = ()=>{
  if(!clickRow.value){return}
  let item = clickRow.value
  const mapPoint = new Point({longitude: item.locationLongitude,latitude: item.locationLatitude, spatialReference: {wkid: 4326}});
   const { x, y } = mapView.toScreen(mapPoint)
   item.x = x
   item.y = y
  const popOption = {
            title:item.farmName||item.farmLandNo,
            farmId:item.farmId,
            companyId:item.companyId,
            farmLandId:item.farmLandId,
            pic:item.pic,
            screenX: item.x+10,
            screenY: item.y+10,
            visible:true,
            mapX: item.longitude,
            mapY: item.latitude,
            btnText:'地块详情',
            values: [
                // {
                //     label: '所属农场',
                //     value: item.farmName
                // },
                {
                    label: '地块编号',
                    value: item.farmLandNo
                },
                {
                    label: '地块名称',
                    value: item.farmLandName
                },
                {
                    label: '地块面积',
                    value:  Number(item.mapAreaSize.toFixed(1))+'亩'
                },
                {
                    label: '位置',
                    value: item.locationAddress
                }
            ],
            footerList:[
                {
                    btnText:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?'申诉地块归属':(item.farmId==userStore.userInfo.farmId?'已认领':'点击认领'),
                    icon:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?'vxe-icon-feedback':(item.farmId==userStore.userInfo.farmId?'vxe-icon-check':'vxe-icon-send'),
                    farmId:item.farmId,
                    color:item.farmId?'#25c289':'#409eff',
                    farmLandId:item.farmLandId,
                    type:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?2:(item.farmId==userStore.userInfo.farmId?0:1),

                },
                {
                    btnText:'地块详情',
                    icon:'vxe-icon-maximize',
                    farmId:item.farmId,
                    color:'#25c289',
                    farmLandId:item.farmLandId,
                    type:3
                }
            ],
            ...item
  }
  popObjct.value = popOption
}
  // 表格行单击处理事件
  const setMapData = (row)=>{
    dropFarmLandId.value = row.farmLandId
    dropFarmLandPic.value = row.pic
    dropFarmLandNo.value = row.farmLandNo
    setSelectLine({row})
        mapView.set({
        zoom:18,
        center: [Number(row.locationLongitude), Number(row.locationLatitude)]
        })
    clickRow.value = row
    showPop.value = true
    getClickData()
    getMapDataLand()
  }

  const toPage = (pages)=>{
    searchInfo.value.page = pages.currentPage
    get_land_list()
  }

  const goBack = ()=>{
    emit('close')
  }
  const goDetail = (row)=>{
    dropFarmLandId.value = row.farmLandId
    dropFarmLandPic.value = row.pic
    showDetail.value = true
  }

//认领地块-移除地块改变颜色
 const changeLandColor =(type,row)=>{
    if(type==1){
        popObjct.value.footerList.forEach((item,index)=>{
           if(index==0){
            item.type=0
            item.btnText='已认领'
           }
        })
    }
    mapList.value.map((item)=>{
        if(item.farmLandId==row.farmLandId){
            item.farmId=(type==1?userStore.userInfo.farmId:0)
        }
        return item
    })
    showPop.value = false
     if (graphicsLayer) {
              const target = graphicsLayer.graphics.items.find((item) => item.attributes.farmLandId == row.farmLandId);
              if (target) {
                target.symbol = {
                  type: 'simple-fill',
                  color:[43, 129, 212, 0],
                  outline: {
                    // color:  '#25c289',
                    color:type==1?'#25c289':[43, 129, 212, 1],
                    width: 1
                  }
                }
        }
    }
 }

 const  btnDelAll = ()=>{
    btnDel(tableData.value.map((item)=>item.farmLandId),'all')
 }

 defineExpose({btnDelAll})
 //移除地块
  const btnDel = async (row,type)=>{
    const info = await VXETable.modal.confirm({
        title:'确认删除认领的地块吗？',
        content:'删除后认领的地块不可见。'
    })
    if(info==='confirm'){
        let res = await releaseFarmland(type=='all'?row:[row.farmLandId])
        if(res.success){
            VXETable.modal.message({ content: '删除成功', status: 'success'})
            showDetail.value = false
            get_land_list() 
            get_farm_count()
            if(type=='all'){
                tableData.value.forEach((item)=>{
                    changeLandColor(0,item)
                })
            }else{
                changeLandColor(0,row)
            }
        }else{
            VXETable.modal.message({ content: res.message, status: 'error'})
        }
    }
  }

const getImageUrl =(graphics)=>{
    return new Promise((resolove) => {
        mapView.goTo(graphics).then(() => {
        mapView.takeScreenshot({
            format: 'png',
            quality: 100,
            width:500,
            height:500,
          }).then((screenshot) => {
            resolove(screenshot.dataUrl);
          })
      })
    })
}


const dataURLtoBlob=(dataUrl,fileName)=> { 
  var arr = dataUrl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  var blob = new Blob([u8arr], { type: mime });
  return new File([blob], fileName, { type: mime });
}
 

    const getPic = async (row)=>{
        const target = graphicsLayer.graphics.items.find((item) => item.attributes.farmLandId == row.farmLandId);
            let baseUrl = await  getImageUrl(target)
            if(baseUrl){
                var file = dataURLtoBlob(baseUrl, `${row.locationAddress}${row.farmLandName}_${new Date().getTime()}.png`);
                const formData = new FormData();
                formData.append('file', file);
            return new Promise(async (resolve, reject) => {
                    resolve(await uploadFile(formData))
            })
        }
    }

    const goEditFarmLand=async (row)=>{
        let res = await tancLand({ 
            farmId:userStore.userInfo.farmId,
            farmLandId: row.farmLandId,
            picSource:row.picSource,
            pic:row.pic
        })
        if(res.success){
            VXETable.modal.message({ content: '认领成功', status: 'success'})
            get_land_list()
            get_farm_count()
            changeLandColor(1,row)
        }else{
            VXETable.modal.message({ content: res.message, status: 'error'})
        }
    }

  //认领地块
  const clickLand =async (row)=>{
    switch (row.type) {  
    case 1:  
     if(row.pic){
            goEditFarmLand(row)
        }else{
            VXETable.modal.message({id: 'loading-msg', content: '正在认领...', status: 'loading',duration:-1 })
            let res = await getPic(row)
            if(res.success){
                VXETable.modal.close('loading-msg')
                goEditFarmLand({...row,...{pic:res.result.pic,picSource:res.result.picSource}})
            }
        }
        break;  
        case 2:  
                const info = await VXETable.modal.confirm({
                confirmButtonText:'确认申诉',
                title:'该地块已被其他农场认领，是否申述？',
                content:'申述处理时间1-3工作日，请耐心等待。'})
                if(info==='confirm'){
                    let res = await claimLand({
                        "applicant":userStore.userInfo.nickName,
                        "applicantFarmId":userStore.userInfo.farmId,
                        "applicantFarmName": userStore.userInfo.FarmName,
                        "disputedFarmId": row.farmId,
                        "disputedFarmName": row.farmName,
                        "disputedParcelLandId":  row.farmLandId,
                        "disputedParcelLocation": row.locationAddress
                    })
                    if(res.success){
                        VXETable.modal.message({ content: '申诉成功', status: 'success'})
                    }else{
                        VXETable.modal.message({ content: res.message, status: 'error'})
                    }
                }
            break;  
        case 3:
        goDetail(row)
        break;
    }
  }

  </script>
  
  <style lang="scss" scoped>
    .receive-land-left-view{
        box-sizing: border-box;
        display: flex;
        flex-flow: column;
        height: 100%;
        padding: 10px 0 0 0;
        //overflow: hidden;
    }
    .land-detail{
        position: absolute;
        z-index: 2005;
        width: auto;
        height: auto;
        left: 330px;
        top: 10px;
        bottom:10px;
        right:10px;
        background-color: #fff;
    }

    .bottom-view-tips{
        position: absolute;
        z-index:99;
        bottom: 10px;
        left:320px;
        display: flex;
        justify-content: flex-start;
        >div{
            height:30px;
            width:80px;
            text-align: center;
            font-size:14px;
            line-height:30px;
            background-color: rgb(253, 209, 67);
            border:1px solid rgb(253, 209, 67);
            color: #fff;
            border-radius:2px;
            margin-right:4px;
        }
    }
  </style>
  